<script setup lang="ts">
import MySwiper from "@/components/mySwiper/index.vue";
import GamePicker from "@/components/gamePicker/index.vue";
import { gameListApi, saveCollectApi, gameUrlApi } from "@/api/home";
import type { GameList, WebIframe } from "@/api/model/home";
import { getIcon } from "@/utils/icon";
import GameWeb from "@/components/gameWeb/index.vue";
import data from "./11.json";
// 这是使用tabs组件的版本
definePageMeta({
  layout: "default-home",
  title: "主页",
  i18n: "menu.home",
});
const userStore = useUserStore();
const { t } = useI18n();
const router = useRouter();
const close = ref(true);

const swiperArr = ref([
  { id: 1, img: "/imgs/banner1.png" },
  { id: 2, img: "/imgs/banner1.png" },
  { id: 3, img: "/imgs/banner1.png" },
  { id: 4, img: "/imgs/banner1.png" },
  { id: 5, img: "/imgs/banner1.png" },
]);
// 各类游戏列表
const categoryList = ref<GameList[]>([]);
const menuAactive = ref(0);
const isContBoxScrollable = ref(false);

// 监听 .menu-cont 是否到达顶部
const checkMenuSticky = () => {
  const menuElement = document.querySelector(".mymenu") as HTMLElement;
  if (!menuElement) return;

  const rect = menuElement.getBoundingClientRect();
  console.log("rect", rect.top);

  // 判断是否已经 sticky 固定在顶部（即 top <= 0）
  if (close.value) {
    isContBoxScrollable.value = rect.top <= adviseHeight.value;
  } else {
    isContBoxScrollable.value = rect.top <= 0;
  }
};
const goAnnouncement = () => {
  router.push("/home/announcement");
};
const goMore = () => {
  router.push("/home/search");
};
const providerArr = ref([
  {
    id: 1,
    name: "PP",
    cont: "哈哈哈哈哈哈哈",
  },
  {
    id: 2,
    name: "PG",
    cont: "哈哈哈哈哈哈哈",
  },
  {
    id: 3,
    name: "LUVA",
    cont: "哈哈哈哈哈哈哈",
  },
  {
    id: 4,
    name: "JILI",
    cont: "哈哈哈哈哈哈哈",
  },
]);
const goLogin = () => {
  router.push("/login");
};
const goRegister = () => {
  router.push("/register");
};
const formatText = (text: string) => {
  return text
    .replace(/享受/g, '<span style="color: #26bceb">享受</span>')
    .replace(/分割/g, '<span style="color: #81d027">分割</span>');
};
const currentIndex = ref(0);
const progressKey = ref(0); // 用于触发动画重播

const onSwipeChange = (index: number) => {
  currentIndex.value = index;
  progressKey.value++; // 每次切换都重置动画
};
const contBox = ref<HTMLElement | null>(null); //  内容的容器
const mySwiperRef = ref(null);
const handleClickTab = async (e: { name: number }) => {
  await nextTick();
  const swiperInstance = mySwiperRef.value;

  if (!swiperInstance || !swiperInstance.gameItemRefs) return;

  const elements = swiperInstance.gameItemRefs;
  const container = contBox.value;
  //  console.log('e',e);
  if (e.name === 0 && container) {
    container.scrollTo({ top: 0, behavior: "smooth" });
  } else {
    const element = elements[e.name - 1];
    if (element && container) {
      // console.log('element',element);
      console.log(99, window.innerHeight);

      container.scrollTo({
        // top: element.offsetTop-175 , // 固定偏移量（可按需调整）
        top: element.offsetHeight * e.name, // 固定偏移量（可按需调整）
        behavior: "smooth",
      });
    }
  }
};
const columns = [
  { value: 1, text: t("home_page.leftMenu.hots") },
  { value: 2, text: t("home_page.leftMenu.slots") },
  { value: 3, text: t("home_page.leftMenu.chess") },
  { value: 4, text: t("home_page.leftMenu.fish") },
  { value: 5, text: t("home_page.leftMenu.person") },
  { value: 6, text: t("home_page.leftMenu.sport") },
  { value: 7, text: t("home_page.leftMenu.lottery") },
];
const showPicker = ref(false);
const handlePickerConfirm = (selectedValues: number[]) => {
  console.log("选中的值:", selectedValues);
  // 处理选中的值
};
const adviseRef = ref();
const adviseHeight = ref();
// 收藏列表数据
const getCollectList = () => {
  return categoryList.value.find((item) => item.gameType === 90)?.list || [];
};
watch(
  () => close.value,
  (newVal: any) => {
    if (!newVal && adviseRef.value) {
      // 广告关闭时可选地清空高度（非必须）
      // adviseHeight.value = 0;
    } else if (adviseRef.value) {
      adviseHeight.value = adviseRef.value.offsetHeight;
    }
  },
  { immediate: true }
);
onMounted(async () => {
  await userStore.getUserInfo()
  if (adviseRef?.value) {
    adviseHeight.value = (adviseRef.value as HTMLElement).offsetHeight;
  }
  await getGameList();
  window.addEventListener("scroll", checkMenuSticky, { passive: true });
});
onBeforeUnmount(() => {
  window.removeEventListener("scroll", checkMenuSticky);
});
// 更新所有游戏项的收藏状态
const updateAllCollectStatus = () => {
  const collectList = getCollectList();

  categoryList.value.forEach((item) => {
    item.list.forEach((game) => {
      game.active = collectList.some(
        (collectGame) => collectGame.gameId === game.gameId
      );
    });
  });
};

// 接受子组件的处理收藏/取消收藏事件值
const updateCollect = (val: { gameId: number; active: boolean }) => {
  const collectCategory = categoryList.value.find(
    (item) => item.gameType === 90
  );
  if (!collectCategory) return;

  if (val.active) {
    // 添加收藏
    const gameToAdd = categoryList.value
      .flatMap((item) => item.list)
      .find((game) => game.gameId === val.gameId);

    if (
      gameToAdd &&
      !collectCategory.list.some((g) => g.gameId === val.gameId)
    ) {
      collectCategory.list.unshift({ ...gameToAdd, active: true });
    }
  } else {
    // 取消收藏
    collectCategory.list = collectCategory.list.filter(
      (game) => game.gameId !== val.gameId
    );
  }

  // 更新所有游戏项的active状态
  updateAllCollectStatus();
};

// 获取所有游戏列表
const getGameList = () => {
  // categoryList.value = data.data;
  gameListApi().then(res => {
    categoryList.value = res || []
    // 初始化时确保所有游戏项的active状态正确
    updateAllCollectStatus();
  })
};
const showGameWeb = ref(false);
// 传给孙组件控制GameWeb的显示
provide("provided-gameWeb", showGameWeb);
const gameWeb = ref<WebIframe>({
  gold: 0,
  name: "",
  // direct: 0,
  webViewUrl: "",
});
const gameClick = (val: any) => {
  showGameWeb.value = true;
  gameWeb.value = val;
};
</script>

<template>
  <div id="mybox">
    <div v-if="showGameWeb" class="iframe fixed overflow-hidden">
      <GameWeb :game-data="gameWeb" @close="showGameWeb = $event" allow="fullscreen" />
    </div>
    <div v-else class="bg-#222628 w-full">
      <!-- 下载广告 -->
      <div class="download fixed top-0 w-full z-1">
        <div ref="adviseRef" class=" py-5 px-3 h-40" v-if="close">
          <div class="flex items-center justify-between">
            <div @click="close = false" class="w-100 h-20">
              <img class="w-20 h-20 absolute top-0 left-0 rounded-2" src="/imgs/download_close.png" />
            </div>
            <div class="download_btn text-12 px-10 py-5 h-full color-#A30806">
              <img src="/imgs/download.png" alt="" class="w-16 h-16 mr-5" />
              <span> {{ t("home_page.nowDown") }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="main" :style="{ 'margin-top': close ? adviseHeight + 'px' : '0px' }">
        <!-- 登录注册 -->
        <div class="login-box px-15 flex justify-between items-center py-15">
          <div class="flex justify-between items-center">
            <div class="bg-#394243 rounded-6 p-7 mr-10">
              <img src="/imgs/more.png" alt="" class="w-15 h-15" @click="showPicker = true" />
            </div>
            <div class="color-#f9f9f9">Rewards</div>
          </div>
          <div class="flex justify-between" v-if="!userStore.isLogin">
            <div class="home-btn sign_in mr-10" @click="goRegister">
              {{ t("home_page.register") }}
            </div>
            <div class="home-btn register" @click="goLogin">
              {{ t("home_page.login") }}
            </div>
          </div>
          <div class="flex justify-between items-center" v-else>
            <div class="info flex justify-between items-center">
              <img src="/imgs/gold_icon.png" alt="" class="w-20" />
              <div class="color-#ffffff font-bold text-14 ml-5">999999</div>
              <img src="/imgs/gold_up.png" alt="" class="w-35" />
            </div>
            <div class="vip">VIP2</div>
          </div>
        </div>
        <!-- 轮播图 -->
        <div class="px-15">
          <van-swipe class="my-swipe" :autoplay="3000" indicator-color="#fefffe" :show-indicators="false"
            @change="onSwipeChange" ref="swipeRef">
            <van-swipe-item v-for="(item, index) in swiperArr" :key="index">
              <img class="w-full h-150 rounded-10" :src="item.img" />
            </van-swipe-item>
          </van-swipe>

          <!-- 自定义指示器 -->
          <div class="custom-indicators">
            <div v-for="(item, index) in 4" :key="index" class="indicator" :class="{ active: index === currentIndex }">
              <div v-if="index === currentIndex" class="indicator-progress" :key="progressKey"></div>
            </div>
          </div>
        </div>
        <!-- 消息通知栏 -->
        <div class="notice mx-15">
          <van-notice-bar @click="goAnnouncement" color="#f6f7f7" background="transparent">
            <template #default>
              <span style="color: #fefffe" v-html="formatText(
                '无论我们能活多久，我们能够享受的只有无法分割的此刻，此外别无其他。'
              )
                " />
            </template>
            <template #left-icon>
              <img src="/imgs/sound.png" class="w-28 h-full" />
            </template>
          </van-notice-bar>
        </div>
        <!-- 菜单-->
        <div class="mymenu sticky z-1" :style="{ top: close ? adviseHeight - 2 + 'px' : '0px' }">
          <div class="menu-cont">
            <!-- 菜单栏 -->
            <van-tabs v-model:active="menuAactive" scrollspy sticky class="px-15" @click-tab="handleClickTab">
              <van-tab v-for="(item, index) in categoryList" :key="item.gameType">
                <template #title>
                  <div class="flex items-center">
                    <img :src="getIcon(item.gameType)" alt="" class="w-22 mr-5"
                      :class="menuAactive == index ? '' : 'inactive'" />
                    <span :class="menuAactive == index ? 'color-#eef3ff' : 'inactive'
                      ">
                      {{ item.name }}</span>
                  </div>
                </template>
              </van-tab>
            </van-tabs>
          </div>
        </div>
        <!-- 游戏滚动内容 -->
        <div ref="contBox" class="boxs" :class="{ scrollable: isContBoxScrollable }">
          <MySwiper :categoryList="categoryList" ref="mySwiperRef" @gameClick="gameClick"
            @updateCollect="updateCollect" />

          <!-- 活动区域 -->
          <div class="px-15">
            <img src="/imgs/activitys.png" alt="" />
          </div>
          <!-- 供应商 -->
          <div class="px-15 flex items-center my-10">
            <img src="/imgs/providers.png" alt="" class="w-25" />
            <div class="color-#c9ccd7 text-14 font-bold">供应商</div>
          </div>
          <div class="provider">
            <div class="provider-item" v-for="item in providerArr" :key="item.id">
              <div class="color-#ffffff text-14 mr-5 opacity-70 font-bold">
                {{ item.name }}
              </div>
              <div class="color-#ffffff text-10">{{ item.cont }}</div>
            </div>
          </div>
          <div class="p-15 color-#c9ccd7 text-14 text-center">
            <div>
              No-microphone statement: The gaming experience provided by
              thiswebsite contains risks. You must be at least 18 years old to
              become aplatform user. You are obliged to comply with the relevant
              onlinegamblingregulations applicable to you, and the platform will
              notbear any responsibility for your illegal behavior.
            </div>
            <div class="mt-15">@xxxbkhdh 2002-2025</div>
          </div>
        </div>
      </div>
      <!-- 更多弹窗 -->
      <GamePicker v-model:show="showPicker" :columns="columns" title="选择游戏" @confirm="handlePickerConfirm" />
      <AppFooter />
    </div>
  </div>
</template>
<style lang="css" scoped>
#mybox {
  position: relative;
}

.iframe {
  width: 100vw;
  height: 100vh;
  /* overflow: hidden; */
  /* 关键 */
  position: fixed;
  /* 固定定位 */
}

.info {
  width: 109px;
  background: url("/imgs/gold_bg.png") no-repeat;
  background-size: 100% 100%;
  padding: 2px 5px;
}

.vip {
  width: 70px;
  background: url("/imgs/v2_bg.png") no-repeat;
  background-size: 100% 100%;
  color: #ffffff;
  font-weight: bold;
  font-size: 12px;
  padding: 3px 0 3px 35px;
}

.provider {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  padding: 0 15px;
}

.provider-item {
  background: #404760;
  display: flex;
  padding: 5px 10px;
  border-radius: 8px;
  border: solid 1px rgba(255, 255, 255, 0.1);
}

.menu-cont {
  background: #282425;
  /* max-height: calc(100vh - 100px); */
}

.boxs {
  overflow-y: hidden;
  max-height: calc(100vh - 100px);
}

.boxs.scrollable {
  overflow-y: scroll;
  -ms-overflow-style: none;
  /* IE/Edge */
  scrollbar-width: none;
  /* Firefox */
}

/* WebKit 浏览器（Chrome/Safari）隐藏滚动条 */
.boxs.scrollable::-webkit-scrollbar {
  display: none;
}

.custom-indicators {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  gap: 5px;
}

.indicator {
  width: 10px;
  height: 3px;
  background: #818495;
  position: relative;
  overflow: hidden;
  border-radius: 50px;
}

.indicator.active {
  width: 30px;
}

.indicator-progress {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: linear-gradient(to right, #ecffc0, #35fa30);
  /* 渐变绿色 */
  animation: progressMove 3s linear forwards;
  border-radius: 1px;
}

@keyframes progressMove {
  0% {
    transform: translateX(-100%);
  }

  100% {
    transform: translateX(0%);
  }
}

.download {
  background: url("/imgs/download_bg.png") no-repeat;
  background-size: 100% 100%;
}

.download_btn {
  display: flex;
  align-items: center;
  background: url("/imgs/download_btn.png") no-repeat;
  background-size: 100% 100%;
}

/* 隐藏滚动条（可选） */
.hide-scrollbar::-webkit-scrollbar {
  display: none;
}

.hide-scrollbar {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.sign_in {
  background: url("/imgs/sign_in.png") no-repeat;
}

.register {
  background: url("/imgs/register.png") no-repeat;
}

.home-btn {
  background-size: 100% 100%;
  color: #f9f9f9;
  text-align: center;
  height: 29px;
  width: 80px;
  padding: 3px 0px;
  font-weight: bold;
  font-size: 14px;
}

.notice {
  background: url("/imgs/ad_bg.png") no-repeat;
  background-size: 100% 100%;
  margin-bottom: -8px;
}

::v-deep .van-notice-bar__wrap {
  font-size: 14px;
}

::v-deep .van-notice-bar {
  margin: 10px 0;
  height: 28px;
  padding: 0;
}

::v-deep .van-tabs__line {
  background: transparent;
  height: 30px;
  padding-bottom: 0;
}

::v-deep .van-tabs__nav--line {
  padding-bottom: 0;
}

.tabs .tab-item {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  background: #ffffff;
}

::v-deep .van-tab {
  color: #ffffff;
}

::v-deep .van-tabs {
  padding: 8px 15px;
}

::v-deep .van-swipe {
  width: 100%;
  padding-bottom: 2px;
  border-radius: 8px;
  background: url("/imgs/banner_bg.png") no-repeat;
  background-size: 100% 100%;
}

::v-deep .van-tabs--line .van-tabs__wrap {
  background: #16161a;
  border-radius: 20px;
}

.inactive {
  filter: brightness(0) saturate(100%) invert(44%) sepia(8%) saturate(697%) hue-rotate(185deg) brightness(91%) contrast(90%);
}

::v-deep .tabs .van-swipe-item .van-tab__panel-wrapper {
  background: #ffffff;
}

::v-deep .van-tabs__nav {
  background: transparent;
}

::v-deep .van-tab--active {
  margin-top: 7px;
  background: url("/imgs/tabs_active_bg.png") no-repeat;
  background-size: 100% 100%;
  height: 30px;
}

::v-deep .van-tab--active img {
  width: 22px;
}

.game-item {
  background: url("/imgs/item_bg.png") no-repeat;
  background-size: 100% 100%;
  position: relative;
}

.people {
  background: url("/imgs/people_bg.png") no-repeat;
  background-size: 100% 100%;
  padding: 2px 5px;
  top: 5px;
  /* width: 80px; */
  position: relative;
}

.people img {
  position: absolute;
}

.more {
  background: url("/imgs/grey_bg.png") no-repeat;
  background-size: 100% 100%;
  padding: 2px 5px;
  font-size: 14px;
  /* width: 80px; */
}

.swiper-container {
  width: 100%;
  height: 100%;
}

.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #d14444;

  /* Center slide text vertically */
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
}
</style>